# 测试围棋逻辑的程序
import json

from src.tool import throw
from src.go import Go
import copy


# 测试集合：
# 单个吃子（角落）
# 1 2
# 1 1
# 2 1
color = 'black'
def parse_x_y(xy):
    parsed = xy.split(' ')
    return parsed


def do_go(x, y):
    temp_board = copy.deepcopy(go.board)
    temp_string = copy.deepcopy(go.string)
    res = go.step_check(x, y)
    if res is False:
        return
    go.do_step(x, y)

    go.combine(x, y)
    print(go.string)
    # 黑走杀白 白走杀黑
    if go.isBlack:
        flag = -1
    else:
        flag = 1
    kill_res = go.kill(x, y, flag)
    print("kill_res = {}".format(kill_res))
    #  杀棋了
    if len(kill_res) > 0:
        for i in range(len(kill_res)):
            killed = go.clean_string(kill_res[i])
            if len(killed) == 1:
                go.robX = killed[0]['x']
                go.robY = killed[0]['y']
            else:
                go.robX = None
                go.robY = None
    else:
        # 没杀就得判断是否自杀
        if go.isBlack:
            self_flag = 1
        else:
            self_flag = -1
        print("判断是否导致自身死棋")
        self_res = go.check_kill(x, y, self_flag)
        print('check_kill res = {}'.format(self_res))
        if self_res is not False:
            go.board = temp_board
            go.string = temp_string
            go.robX = None
            go.robY = None

    # 每次落子取反 黑白交替
    go.isBlack = not go.isBlack
    print("处理后的棋盘为->\n", go.board)


if __name__ == '__main__':
    # 循环读入
    go = Go()
    go.init()
    option = input("按1读取棋谱文件，输入其他进行手动落子\n")
    if int(option) != 1:
        while True:
            print("目前是否是黑落子->{}".format(go.isBlack))
            xy = input("输入xy坐标 按空格分割\n")
            args = parse_x_y(xy)
            if len(args) < 2:
                print("缺少参数\n")
                continue
            x = int(args[0])
            y = int(args[1])
            print("x = {},y = {}".format(x, y))
            if x < 1 or x > 19 or y < 1 or y > 19:
                print("x，y坐标范围必须为1-19\n")
                continue

            x = x - 1
            y = y - 1

            go.go_logic(x, y, color)
            if color == 'black':
                color = 'white'
            else:
                color = 'black'

    else:
        goban = json.load(open('./go_ban.json'))
        print("目前的棋谱", goban)
        ban = input("选择需要的棋谱\n")
        if ban not in goban:
            print("棋谱[{}]不存在".format(ban))
        arr = goban[ban]
        print(arr)
        for i in range(len(arr)):
            single = arr[i]
            x_y = single.split(' ')
            x = int(x_y[0])
            y = int(x_y[1])
            # 棋谱是符合人类常识的 所以都得减去1
            x = x - 1
            y = y - 1
            print("x->{},y->{}".format(x, y))
            do_go(x, y)
